<?php
class Dimension extends CActiveRecord {
	public static function model($className=__CLASS__)	{
		return parent::model($className);
	}
	public function getDbConnection() {
      $db = Yii::app()->controller->module->db;
      return Yii::createComponent($db);
    }
	public function tableName() {
		return 'dimension';
	}
	public function rules()	{
		return array(
			array('name', 'required'),
			array('left, right, root, parent, level', 'numerical', 'integerOnly'=>true),
			array('name, pathtext', 'length', 'max'=>30),
			array('path', 'safe'),
			array('id, name, left, right, root, parent, path, pathtext, level', 'safe', 'on'=>'search'),
		);
	}
	public function relations() {
		return array(
		);
	}
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Name',
			'left' => 'Left',
			'right' => 'Right',
			'root' => 'Root',
			'parent' => 'Parent',
			'path' => 'Path',
			'pathtext' => 'Pathtext',
			'level' => 'Level',
		);
	}
	public function search() {
		$criteria=new CDbCriteria;
		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('left',$this->left);
		$criteria->compare('right',$this->right);
		$criteria->compare('root',$this->root);
		$criteria->compare('parent',$this->parent);
		$criteria->compare('path',$this->path,true);
		$criteria->compare('pathtext',$this->pathtext,true);
		$criteria->compare('level',$this->level);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function behaviors() {
		return array(
			'nestedSetBehavior'=>array(
				'class'=>'ext.behaviors.NestedSetBehavior',
				'leftAttribute'	=>'left',
				'rightAttribute'	=>'right',
				'levelAttribute'	=>'level',
				'rootAttribute'	=>'root',
			),
		);
	}
	public function tree_save() {
		if (!$this->parent) {
			$this->saveNode();
			return $this;
		}
		else {
			$parent = Dimension::model()->findByPk($this->parent);
			if ($parent) {
				$this->appendTo($parent);
				return $this;
			}
			return null;
		}
	}
}